/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Formularios;

import com.thoughtworks.xstream.XStream;
import hispamail.CDir;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.RowSorter;
import javax.swing.SortOrder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

/**
 *
 * @author MCS
 */
public class JLibreta extends javax.swing.JDialog {

    private static ArrayList<CDir> Correos;

    /**
     * Creates new form JLibreta
     *
     * @param parent
     * @param modal
     * @param Correos
     */
    public JLibreta(java.awt.Frame parent, boolean modal, ArrayList<CDir> Correos) {
        super(parent, modal);
        JLibreta.Correos = Correos;
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTLibreta = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Libreta de Direcciones");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jTLibreta.setAutoCreateRowSorter(true);
        jTLibreta.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Nombre", "Correo", "Enviar"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.Boolean.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jTLibreta.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jTLibreta.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(jTLibreta);
        jTLibreta.getAccessibleContext().setAccessibleName("");

        jButton1.setText("Añadir Correo");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Borrar Correo");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Aceptar");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(87, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton3)
                        .addGap(18, 18, 18)
                        .addComponent(jButton2)
                        .addGap(17, 17, 17)
                        .addComponent(jButton1))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(77, 77, 77))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(55, 55, 55)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 247, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(jButton3))
                .addContainerGap(117, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        /*
         jTLibreta.setAutoCreateRowSorter(true);
         List<RowSorter.SortKey> sortKeys = new ArrayList<>();
         sortKeys.add(new RowSorter.SortKey(0, SortOrder.ASCENDING));
         jTLibreta.getRowSorter().setSortKeys(sortKeys);

         jTLibreta.changeSelection(0, 0, false, false);
        
         DefaultTableModel modelo = new DefaultTableModel();
         modelo = (DefaultTableModel) jTLibreta.getModel();
         //TableColumn columna = tabla.getColumn("columna 1");
         TableColumn columna = jTLibreta.getColumn("Enviar");
         columna.setPreferredWidth(1);
        
         jTLibreta.setModel(modelo);
         */
        jTLibreta.setAutoCreateRowSorter(true);
        List<RowSorter.SortKey> sortKeys = new ArrayList<>();
        sortKeys.add(new RowSorter.SortKey(0, SortOrder.ASCENDING));
        jTLibreta.getRowSorter().setSortKeys(sortKeys);

        jTLibreta.changeSelection(0, 0, false, false);

        //Asignamos los anchos de las columnas
        int anchoColumna = 1;
        int ancho = jTLibreta.getWidth();
        TableColumnModel modeloColumna = jTLibreta.getColumnModel();
        TableColumn columnaTabla;
        for (int i = 0; i < jTLibreta.getColumnCount(); i++) {
            columnaTabla = modeloColumna.getColumn(i);
            switch (i) {
                case 0:
                    anchoColumna = (40 * ancho) / 100;
                    break;
                case 1:
                    anchoColumna = (50 * ancho) / 100;
                    break;
                case 2:
                    anchoColumna = (10 * ancho) / 100;
                    break;
            }
            columnaTabla.setPreferredWidth(anchoColumna);
        }
        
        ArrayList<CDir> Crr=null;
                
        //Leemos el la libreta de correos si existe
        File ruta = new File(JFrameInicio.libreta);
        if (ruta.exists()) {
            //Cargamos la tabla con la libreta de direcciones
            XStream xstream = new XStream();
            xstream.alias("libreta", ArrayList.class);
            FileInputStream flip = null;
            try {
                flip = new FileInputStream(JFrameInicio.libreta);
            } catch (FileNotFoundException ex) {
                Logger.getLogger(JLibreta.class.getName()).log(Level.SEVERE, null, ex);
            }
            
            Crr = (ArrayList<CDir>) xstream.fromXML(flip);
            try {
                flip.close();
            } catch (IOException ex) {
                Logger.getLogger(JLibreta.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        DefaultTableModel modelo;
        modelo = (DefaultTableModel) jTLibreta.getModel();

        //Lleno la tabla con las direcciones
        if(Crr!=null)
        for (int i = 0; i < Crr.size(); i++) {
            Object[] fila = new Object[3];
            fila[0] = Crr.get(i).getNombre();
            fila[1] = Crr.get(i).getCorreo();
            fila[2] = false;

            modelo.addRow(fila);
        }
        jTLibreta.setModel(modelo);
        if (jTLibreta.getModel().getRowCount() > 0) {
            jTLibreta.setRowSelectionInterval(0, 0);
        }
    }//GEN-LAST:event_formWindowOpened

    //Añade
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        Object[] fila = new Object[3];
        fila[0] = "";
        fila[1] = "";
        fila[2] = true;

        DefaultTableModel modelo;
        modelo = (DefaultTableModel) jTLibreta.getModel();
        modelo.addRow(fila);

        jTLibreta.setModel(modelo);

        jTLibreta.setRowSelectionInterval(0, 0);
        jTLibreta.requestFocus();
        jTLibreta.editCellAt(0, 0);
    }//GEN-LAST:event_jButton1ActionPerformed

    //borra
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        int i = jTLibreta.getSelectedRow();
        if (i == -1) {
            return;
        }

        DefaultTableModel md = (DefaultTableModel) jTLibreta.getModel();

        md.removeRow(i);
        jTLibreta.setModel(md);
        if (jTLibreta.getRowCount() > 0) {
            jTLibreta.setRowSelectionInterval(0, 0);
        }

    }//GEN-LAST:event_jButton2ActionPerformed

    //Salimos de la ventana
    //devolvemos la lista de los correos seleccionados
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        int tot = jTLibreta.getRowCount();
        ArrayList<CDir> Todos = new ArrayList<>();

        for (int i = 0; i < tot; i++) {
            CDir elto = new CDir((String) jTLibreta.getValueAt(i, 0), (String) jTLibreta.getValueAt(i, 1));
            if (jTLibreta.getValueAt(i, 2).equals(true)) {
                Correos.add(elto);
            }
            Todos.add(elto);
        }

        //guardamos el registro de libreta con xstream
        XStream xstream = new XStream();
        xstream.alias("libreta", ArrayList.class);
        FileOutputStream flop;
        try {
            flop = new FileOutputStream(JFrameInicio.libreta);
            xstream.toXML(Todos, flop);
            flop.close();

        } catch (FileNotFoundException ex) {
            Logger.getLogger(JLibreta.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(JLibreta.class.getName()).log(Level.SEVERE, null, ex);
        }

        dispose();
    }//GEN-LAST:event_jButton3ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JLibreta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JLibreta dialog = new JLibreta(new javax.swing.JFrame(), true, Correos);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTLibreta;
    // End of variables declaration//GEN-END:variables
}
